package com.ad_hccm.controller;


import com.ad_hccm.domain.User;
import com.ad_hccm.interceptor.TokenUtil;
import com.ad_hccm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService service;
    @Autowired
    TokenUtil tokenUtil;

    @PostMapping
    public Result register(@RequestBody User domain){
        domain.setRole("user");
        boolean flag = service.save(domain);
        String msg = flag ? "注册成功" : "注册失败" ;
        return new Result( flag ? Code.SAVE_OK : Code.SAVE_ERR, flag, msg);
    }

    @PutMapping
    public Result login(@RequestBody User domain) {
        System.out.println(domain);
        User user = service.getByAccount(domain.getAccount());
        boolean flag = user!=null ? domain.getPassword().equals(user.getPassword()) : false;
        String token=null;
        if(flag)token = tokenUtil.getToken(user.getAccount(), user.getRole());
        String msg = flag ? "登录成功" : "登录失败" ;
        return new Result(flag ? Code.OK : Code.ERR , token , msg);
    }
}
